# -*- coding: utf-8 -*-
#!/usr/bin/env python
import logging,datetime
import urllib,urllib2

WETHER_API = u'http://www.google.com/ig/api?hl=zh-cn&weather=%s'
WETHER_MESSAGE = u'今天%s,气温%s-%s.明天%s,气温%s-%s.http://sms.fengsage.com'

class WeatherCollect():
    
    city = ''
    url = ''
    
    def __init__(self,url,city=''):
        self.city = city
        self.url = url
        
    def __read_page(self):
        #模拟浏览器
        header = { 'Host':'www.google.com',\
                   'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9',\
                   'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\
                   'Accept-Language':'zh-cn,zh;q=0.5'}
        
        req = urllib2.Request(self.url,None,header)
        
        try:
            response = urllib2.urlopen(req)
        except:
            print 'open exception'
            return 0
#        print response.read()
        html_content = response.read()
#        print html_content
        return html_content
        
    
    def get_weather(self):
        global WETHER_MESSAGE
        import re
        xml = self.__read_page()
#        try:
        td_condition = re.findall(u'<condition data="([^>]*)"/>', xml)[1].decode('utf-8') #雨
        td_low = re.findall(u'<low data="([^>]*)"/>', xml)[0] #当天最低气温
        td_high = re.findall(u'<high data="([^>]*)"/>', xml)[0] #当天最高气温
#            td_wind = re.findall('<wind_condition data="([^>]*)"/>', xml)[0] #风向

        tm_condition = re.findall(u'<condition data="([^>]*)"/>', xml)[2].decode('utf-8') #雨
        tm_low = re.findall(u'<low data="([^>]*)"/>', xml)[1] #明天最低气温
        tm_high = re.findall(u'<high data="([^>]*)"/>', xml)[1] #明天最高气温        
    
        msg = WETHER_MESSAGE%(td_condition,td_low,td_high,tm_condition,tm_low,tm_high)
#            msg = WETHER_MESSAGE%(td_m_condition,td_high,td_n_condition,td_low,tm_m_condition,tm_high,tm_n_condition,tm_low)
        return msg
#        except :
#            return None

if __name__=="__main__":
    w = WeatherCollect('http://www.google.com/ig/api?hl=zh-cn&weather=jiaxing')
    print w.get_weather()